﻿using Combination.Model;
using System;
using System.Linq;

namespace Combination.UI
{
    public delegate ResponseValidationResult FormValidateHandle(object dataContext);
    public class FormPage : BasePage
    {
        /// <summary>
        /// 自动验证表单参数前执行,；若返回验证失败，则不再执行自动验证表单参数
        /// </summary>
        public FormValidateHandle BeforeFormValidateHandle { get; set; }

        /// <summary>
        /// 自动验证表单参数后执行；若自动验证表单失败，则不执行该验证。
        /// </summary>
        public FormValidateHandle AfterFormValidateHandle { get; set; }

        /// <summary>
        /// 验证DataContext绑定对象的属性
        /// </summary>
        public virtual ResponseValidationResult ValidateDataContext()
        {
            var data = this.DataContext;
            if (BeforeFormValidateHandle != null)
            {
                ResponseValidationResult beforeRet = null;
                //验证表单参数前,并且发送数据给订阅
                this.Dispatcher.Invoke(new Action(() =>
                {
                    try
                    {
                        beforeRet = BeforeFormValidateHandle.Invoke(data) ?? ResponseValidationResult.Ok();
                    }
                    catch
                    {
                        beforeRet = ResponseValidationResult.Error("系统异常");
                    }
                }));
                if (!beforeRet.CheckAccess)
                {
                    return beforeRet;
                }
            }
            //验证数据有效性
            var autoRets = AttributeValidation.Validate(data);
            if (autoRets.Count > 0)
            {
                return ResponseValidationResult.Error(string.Join(Environment.NewLine, autoRets.Select(p => p.Message)));
            }
            if (AfterFormValidateHandle != null)
            {
                ResponseValidationResult afterRet = null;
                //验证表单参数后,并且发送数据给订阅
                this.Dispatcher.Invoke(new Action(() =>
                {
                    try
                    {
                        afterRet = AfterFormValidateHandle.Invoke(data) ?? ResponseValidationResult.Ok();
                    }
                    catch
                    {
                        afterRet = ResponseValidationResult.Error("系统异常");
                    }
                }));

                if (!afterRet.CheckAccess)
                {
                    return afterRet;
                }
            }
            return ResponseValidationResult.Ok();
        }
    }

}
